<template>
  <div>
    <el-dialog v-drag width="90%" :title="!dataForm.prescriptionId ? '新增处方单' : '修改处方单'" :close-on-click-modal="false" :visible.sync="visible">
      <el-form :model="dataForm" :inline="true" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
        <el-form-item label="开方单位" prop="prescriptionUnit">
          <el-select size="mini" @focus="getDicts('PRESCRIPTION_UNIT')" @click="getDicts('PRESCRIPTION_UNIT')" v-model="dataForm.prescriptionUnit"  clearable placeholder="请选择">
            <el-option v-for="item in prescriptionUnits " :key="item.itemId" :label="item.label"  :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处方单号" prop="prescriptionNo">
          <el-input size="mini" v-model="dataForm.prescriptionNo" placeholder="处方单号" disabled clearable></el-input>
        </el-form-item>
        <el-form-item label="单据日期" prop="prescriptionDate">
          <el-date-picker size="mini" style="width:100%;" v-model="dataForm.prescriptionDate" value-format="yyyy-MM-dd"
            type="date" clearable placeholder="单据日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处方类型" prop="prescriptionType">
          <el-select size="mini" @focus="getDicts('PRESCRIPTION_TYPE')" @click="getDicts('PRESCRIPTION_TYPE')" v-model="dataForm.prescriptionType"  clearable placeholder="请选择">
            <el-option v-for="item in prescriptionTypes " :key="item.itemId" :label="item.label"  :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开方人" prop="prescriptionUser">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.prescriptionUser" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处方审核人" prop="auditor">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.auditor" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处方复核人" prop="reviewer">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.reviewer" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购买人" prop="buyerName">
          <el-input size="mini" v-model="dataForm.buyerName" placeholder="购买人" clearable></el-input>
        </el-form-item>
        <el-form-item label="购买人手机号" prop="buyerMobile">
          <el-input size="mini" v-model="dataForm.buyerMobile" placeholder="购买人手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="购买人身份证号" prop="buyerCardId">
          <el-input size="mini" v-model="dataForm.buyerCardId" placeholder="购买人身份证号" clearable></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input size="mini" v-model="dataForm.address" placeholder="地址" clearable></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input size="mini" v-model="dataForm.age" placeholder="年龄" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select size="mini" @focus="getDicts('SEX')" @click="getDicts('SEX')" v-model="dataForm.gender"  clearable placeholder="请选择">
            <el-option v-for="item in genders " :key="item.itemId" :label="item.label"  :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker size="mini" style="width:100%;" v-model="dataForm.birthday" value-format="yyyy-MM-dd"
            type="date" clearable placeholder="出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处方剂数" prop="prescriptionDosis">
          <el-input size="mini" v-model="dataForm.prescriptionDosis" placeholder="处方剂数" clearable></el-input>
        </el-form-item>
        <el-form-item label="方剂用法" prop="prescriptionUsage">
          <el-select size="mini" @focus="getDicts('PRESCRIPTION_USAGE')" @click="getDicts('PRESCRIPTION_USAGE')" v-model="dataForm.prescriptionUsage"  clearable placeholder="请选择">
            <el-option v-for="item in prescriptionUsages " :key="item.itemId" :label="item.label"  :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="疾病名称" prop="diseasesName">
          <el-input size="mini" v-model="dataForm.diseasesName" placeholder="疾病名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="确诊疾病" prop="patientDiseases">
          <el-input size="mini" v-model="dataForm.patientDiseases" placeholder="确诊疾病" clearable></el-input>
        </el-form-item>

        <el-form-item label="过敏史" prop="guoMinDetail">
          <el-input type="textarea" size="mini" v-model="dataForm.guoMinDetail" placeholder="过敏史" clearable></el-input>
        </el-form-item>
        <el-form-item label="患者主诉" prop="patientDescription">
          <el-input type="textarea" size="mini" v-model="dataForm.patientDescription" placeholder="患者主诉" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" size="mini" v-model="dataForm.remark" placeholder="备注" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否远程审方" prop="isRemoteAudit">
          <el-checkbox  type="checkbox" v-model="dataForm.isRemoteAudit" placeholder="是否远程审方" clearable></el-checkbox>
        </el-form-item>
        <el-form-item label="是否后补" prop="isCompleteLater">
          <el-checkbox  v-model="dataForm.isCompleteLater" placeholder="是否后补" clearable></el-checkbox>
        </el-form-item>
        <el-form-item label="处方图片" prop="prescriptionUrl">
          <el-upload
            :action="uploadUrl"
            :on-preview="handleImgPreview"
            :on-remove="handleImgRemove"
            :on-success="handImgSuccess"
            :before-upload="handleBeforeUpload"
            :headers="headers"
            :file-list="dataForm.prescriptionUrl"
            :drag="false"
            list-type="picture"
            name="file"
            :data="uploadData">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <!-- 子表 -->
        <el-divider></el-divider>
        <el-form-item>
          <el-button class="line-button" size="mini" circle type="primary" @click="addRow()"><span
              class="icon iconfont">&#xe664;</span></el-button>
         <el-button class="line-button" size="mini" circle type="danger" @click="deleteRows()"><span
              class="icon iconfont">&#xe813;</span></el-button>
        </el-form-item>

      <!-- 字表 -->

        <el-table :data="dataForm.itemList" border size="mini" class="item-table" height="250"
          @selection-change="selectionChangeHandle" ref="itemTable"
          :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
          <el-table-column type="selection" header-align="center" align="center" width="50">
          </el-table-column>
          <el-table-column prop="productCode" header-align="center" width="150" align="center" label="药品编码">
            <template slot-scope="scope">
                <div class="product-code-box" v-if="scope.row.productCode == ''">
                  <el-form-item :prop="'itemList.'+scope.$index+'.productCode'" :rules="dataRule.productCode">
                    <el-input size="mini" v-model="scope.row.productCode" disabled class="product-code-input"
                      @blur='blurInput(scope.row, "productCode", scope.row.productCode)' v-focus>
                    </el-input>
                  </el-form-item>
                  <el-button size="mini" class="chose-button"  @click="selectproduct(scope.row)"><span
                      class="icon iconfont">&#xe68e;</span></el-button>
                </div>
              <span v-else>{{scope.row.productCode}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="productName" header-align="center" width="180" align="center" label="药品名称">
          </el-table-column>
          <el-table-column prop="tradePrice" header-align="center" width="130" align="center" label="批发价">
          </el-table-column>
          <el-table-column prop="buyNum" header-align="center" width="130" align="center" label="购买数量">
            <template slot-scope="scope">
              <el-form-item :prop="'itemList.'+scope.$index+'.buyNum'" :rules="dataRule.buyNum">
                <el-input size="mini" v-model="scope.row.buyNum"
                type="number" :min="1"  oninput="value=value.replace(/^0|[^0-9]/g, '')"
                  @blur='blurInput(scope.row, "buyNum", scope.row.buyNum)' v-focus> </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="oldMemberPrice" header-align="center" width="100" align="center" label="原会员价">
          </el-table-column>
          <el-table-column prop="newMemberPrice" header-align="center" width="130" align="center" label="新会员价">
            <template slot-scope="scope">
              <el-form-item :prop="'itemList.'+scope.$index+'.newMemberPrice'" :rules="dataRule.newMemberPrice">
                <el-input size="mini" v-model="scope.row.newMemberPrice" type="number"
                  @blur='blurInput(scope.row, "newMemberPrice", scope.row.newMemberPrice)'>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="barCode" header-align="center" width="120" align="center" label="条码">
          </el-table-column>
          <el-table-column prop="genericName" header-align="center" width="180" align="center" label="通用名称">
          </el-table-column>
          <el-table-column prop="standard" header-align="center" width="140" align="center" label="规格">
          </el-table-column>
          <el-table-column prop="unit" header-align="center" align="center" label="单位">
          </el-table-column>
          <el-table-column prop="producingArea" header-align="center" width="180" align="center" label="产地">
          </el-table-column>
          <el-table-column prop="produceFactory" header-align="center" width="180" align="center" label="生产单位">
          </el-table-column>
          <el-table-column prop="approvalNo" header-align="center" width="140" align="center" label="批准文号">
          </el-table-column>
          <el-table-column prop="dosageForm" header-align="center" width="160" align="center" label="剂型">
          </el-table-column>
          <el-table-column prop="remark" header-align="center" width="150" align="center" label="备注">
            <template slot-scope="scope">
              <el-input size="mini" v-model="scope.row.remark" type="textarea"
                @blur='blurInput(scope.row, "remark", scope.row.remark)' autosize>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" icon="el-icon-minus" class="delete-button"
                @click.native.prevent="deleteRow(scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="visible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-drag title="图片预览" :visible.sync="imgDialogVisible" width="50%">
      <el-image style="width: 100%;" :src="previewPath" ></el-image>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    data() {
      return {
        visible: false,
        dataForm: {
          prescriptionId: 0,
          prescriptionNo: '',
          prescriptionDate: this.getNowDate(),
          prescriptionUnit: '',
          prescriptionUser: '',
          prescriptionUrl: '',
          buyerName: '',
          buyerMobile: '',
          buyerCardId: '',
          auditor: '',
          auditorId: '',
          reviewerId: '',
          reviewer: '',
          address: '',
          recipeDate: '',
          age: '',
          prescriptionType: '',
          isRemoteAudit: '',
          isCompleteLater: '',
          gender: '',
          birthday: '',
          patientDiseases: '',
          guoMinDetail: '',
          medicalHistory: '',
          prescriptionDosis: '',
          prescriptionUsage: '',
          remark: ''
        },
        prescriptionUnits: [],
        prescriptionTypes: [],
        prescriptionUsages: [],
        genders:[],
        users:[],
        oldData: {},
        showInput: "",
        dataListSelections: [],
        currentProduct: {},
        dataRule: {
          prescriptionNo: [{
            required: true,
            message: '处方单号不能为空',
            trigger: 'blur'
          }],
          prescriptionDate: [{
            required: true,
            message: '开放日期不能为空',
            trigger: 'blur'
          }],
          prescriptionUnit: [{
            required: true,
            message: '开方单位不能为空',
            trigger: 'blur'
          }],
          prescriptionUser: [{
            required: true,
            message: '开方人不能为空',
            trigger: 'blur'
          }],
          prescriptionUrl: [{
            required: true,
            message: '处方图片路径不能为空',
            trigger: 'blur'
          }],
          buyerName: [{
            required: true,
            message: '购买人不能为空',
            trigger: 'blur'
          }],
          auditor: [{
            required: true,
            message: '处方审核人不能为空',
            trigger: 'blur'
          }],
          reviewer: [{
            required: true,
            message: '处方复核人不能为空',
            trigger: 'blur'
          }],
          prescriptionType: [{
            required: true,
            message: '处方类型不能为空',
            trigger: 'blur'
          }],
          patientDiseases: [{
            required: true,
            message: '确诊疾病不能为空',
            trigger: 'blur'
          }],
        }
      }
    },
    methods: {
      init(id) {
        this.dataForm.prescriptionId = id || 0
        this.visible = true
        this.$nextTick(async () => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.prescriptionId) {
            const res = await this.$http({
              url: `/sale/saleprescriptionorder/info/${this.dataForm.prescriptionId}`,
              method: 'get',
              params: this.$http.adornParams()
            })
            let data = res.data
            if (data && data.code === 0) {
              data.salePrescriptionOrder.isRemoteAudit = data.salePrescriptionOrder.isRemoteAudit == 1 ? true: false
              data.salePrescriptionOrder.isCompleteLater = data.salePrescriptionOrder.isCompleteLater == 1 ? true: false
              this.dataForm = data.salePrescriptionOrder

            }
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (valid) {
            this.dataForm.isRemoteAudit = this.dataForm.isRemoteAudit ? 1: 0
            this.dataForm.isCompleteLater = this.dataForm.isCompleteLater ? 1: 0
            const res = await this.$http({
              url: `/sale/saleprescriptionorder/${!this.dataForm.prescriptionId ? 'save' : 'update'}`,
              method: 'post',
              data: this.$http.adornData(this.dataForm)
            })
            let data = res.data
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          }
        })
      },
      async getDicts(type) {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': type
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          if(type === 'PRESCRIPTION_UNIT'){
            this.prescriptionUnits = data.data
          }else if(type === 'PRESCRIPTION_TYPE'){
            this.prescriptionTypes = data.data
          }else if(type === 'SEX'){
            this.genders = data.data
          }else if(type === 'PRESCRIPTION_USAGE'){
            this.prescriptionUsages = data.data
          }
        }
      },
      async getUsers() {
        const res = await this.$http({
          url: `/sys/user/listUsers`,
          method: 'get',
          params: this.$http.adornParams()
        })
        let data = res.data
        if (data && data.code === 0) {
          this.users = data.data
        }
      },
      setUsers() {
        this.users.forEach((item) => {
          if (this.dataForm.auditor == item.username) {
            this.dataForm.auditorId = item.userId;
          } else if (this.dataForm.reviewer == item.username) {
            this.dataForm.reviewerId = item.userId;
          }
        });
      },
      blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
        }
        this.showInput = ""
      },
      addRow() {
        let item = {
          rowNum: new Date().getTime(),
          detailId: undefined,
          adjustPriceId: '',
          adjustPriceNo: '',
          productId: '',
          productCode: '',
          genericName: '',
          standard: '',
          unit: '',
          producingArea: '',
          produceFactory: '',
          approvalNo: '',
          dosageForm: '',
          barCode: '',
          tradePrice: 0,
          oldSalePrice: 0,
          newSalePrice: 0,
          oldMemberPrice: 0,
          newMemberPrice: 0,
          remark: ''
        }
        this.dataForm.itemList.push(item)
      },
      deleteRows() {
        this.dataListSelections.forEach((val, index) => {
          this.dataForm.itemList.forEach((v, i) => {
            if (val.rowNum === v.rowNum) {
              // i 为选中的索引
              this.dataForm.itemList.splice(i, 1)
            }
          })
        })
        // 删除完数据之后清除勾选框
        this.$refs.itemTable.clearSelection()
      },
      //第三：点击 — 号执行删除一行的方法
      deleteRow(index) {
        //利用数组的splice方法，将该index数据删除
        this.dataForm.itemList.splice(index, 1);
      },
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      selectproduct(row) {
        this.productSelectVisible = true
        this.$nextTick(() => {
          this.$refs.productSelectRef.init()
          // this.$refs['productSelectRef'].init()
        })
      },
    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .el-select{
    width: 100%;
    max-width: 100%;
  }
  .el-dialog__body {
    padding: 5px 20px 30px 20px;
  }

  .product-code-box {
    display: flex;
    justify-content: right;
    align-items: center;

    .product-code-input {
      background-color: #fff;

      .el-input__inner {
        border: 0px !important;
        background-color: #fff;
      }
    }
    .chose-button {
      margin: 0 0 10px 0;
      height: 30px;
      width: 18px;
      padding: 3px 1px;
      margin-left: 2px;
      background-color: #e4f3f7;
    }
  }

  .el-divider {
    margin-bottom: 5px;
  }

  .icon {
    margin-right: 0px;
  }

  .delete-button {
    padding: 3px 5px;
  }

  .el-textarea__inner {
    line-height: 1 !important;
  }
  .el-date-picker{
    width: 100%;
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
     width: auto;
  }

  .el-form-item__error{
    padding-top: 0px!important;
    z-index: 99;
  }
</style>
